<template>
  <cj-popup v-if="appConfig" v-model="showBind" position="bottom" round :closeable="!notAllowClose" :closeOnClickOverlay="!notAllowClose" @closed="handerChose">
    <header class="c-ph24 c-flex-row c-aligni-center c-pt30 c-fs24 c-fw-b">
      <img :src="appConfig.logo" class="c-ww40 c-hh40 c-br10" alt="logo" />
      <span class="c-pl8 c-maxw400 c-text-ellipsis1">{{ appConfig.companyName }}</span>
      <span class="c-pl8">申请</span>
    </header>

    <article v-if="curStep == 1 && isInit == 1" class="c-ph24">
      <template v-if="!showMobile">
        <section class="c-flex-row c-aligni-center c-pv30 c-bd-b1-f6 c-p">
          <input type="tel" v-model="mobile" placeholder="请输入您的手机号" class="c-fs26 c-lh36 c-bd0 c-bg-transparent c-w100" />
        </section>
        <section class="c-flex-row c-aligni-center c-pv30 c-bd-b1-f6 c-p">
          <input type="tel" v-model="imgCode" placeholder="请输入图形验证码" class="c-fs26 c-lh36 c-bd0 c-bg-transparent c-w0 c-flex-grow1" />
          <img :src="$addXossFilter(codeImgInfo.img)" @click="tapGetImgCode" class="c-ww144 c-hh48 c-ml20" alt="" />
        </section>
        <section class="c-flex-row c-aligni-center c-pv30 c-bd-b1-f6 c-p">
          <input v-model="code" placeholder="请输入验证码" class="c-fs26 c-lh36 c-bd0 c-bg-transparent c-w0 c-flex-grow1" />
          <div class="c-fs26 c-fc-xblue c-lh36" @click="tapGetVcode">{{ codeText }}</div>
        </section>
        <section v-if="protocolInfo" @click="tapChangeAgreement" class="c-lh32 c-fs22 c-fc-07C160 c-mt30 c-flex-row">
          <!-- <i v-show="!isCheckAgreement" class="iconfont c-fs24 c-fc-gray c-lh32">&#xe872;</i>
          <i v-show="isCheckAgreement" class="iconfont c-fs24 c-fc-07C160 c-lh32">&#xe871;</i> -->
          <div class="c-mt4 c-ww24 c-hh24 c-br4 c-flex-row c-flex-center c-flex-shrink0" :class="isCheckAgreement ? 'c-bg-07C160':'c-bd2-gray'">
            <i class="iconfont c-fc-white c-fs18 c-lh18">&#xe76c;</i>
          </div>
          <div class="c-textAlign-l c-pl8">
            <span class="c-fc-xblack">已阅读并同意</span>
            <template v-if="isAndroidApp || isiOSApp">
              <span @click.stop="tapToAppProtocol(protocolInfo.useProtocolUrl)">《用户服务协议》</span>
              <span @click.stop="tapToAppProtocol(protocolInfo.privacyProtocolUrl)">《隐私政策》</span>
            </template>
            <template v-else>
              <span @click.stop="tapProtocol(item)" v-for="(item, index) in protocolInfo" :key="index">《{{ item.name }}》</span>
            </template>
          </div>
        </section>
      </template>
      <template v-else>
        <section class="c-ph24 c-flex-row c-aligni-center c-fs28 c-fw-b c-pv30">
          <span>授权</span>
          <span class="c-maxw400 c-text-ellipsis1">{{ appConfig.companyName }}</span>
          <span>手机号</span>
        </section>
        <section class="c-flex-row c-aligni-center c-fs28 c-pv30 c-bd-b1-f6 c-bd-t1-f6">
          <span>{{ showMobile }}</span>
          <i class="c-ml-auto iconfont icon-gougou c-fc-45B930 c-fs40"></i>
        </section>
        <section @click="tapUseOtherMobile" class="c-fc-xblue c-fs20 c-mt24">使用其他手机号码</section>
      </template>

    </article>
    <article v-if="curStep == 2 && isInit == 1" class="c-ph24 c-pt10">
      <section v-if="isNeedFillArea" class="c-flex-row c-aligni-center c-fs28 c-pv30 c-bd-b1-f6 c-p c-pl20">
        <div class="c-fs32 c-fc-xmlred c-pa c-p-l0 c-p-t36">*</div>
        <div v-if="isOpenGetLocation" @click="tapGetLocation" class="c-w90 c-h c-flex-row c-aligni-center">
          <div v-if="addrValue && addrValue.length" class="c-fs24 c-lh34 c-fc-xblack">123</div>
          <div v-else class="c-fs24 c-lh34 c-fc-sgray">请点击定位</div>
          <i class="iconfont c-fc-sgray">&#xe905;</i>
        </div>
        <group v-else>
          <x-address title="" v-model="addrValue" :list="addressData" placeholder="请选择所在地(必填)" @on-hide="handerHideAddress" value-text-align="left" class="c-fs24 c-w100 c-lh34"></x-address>
        </group>
        <div v-if="errorTipName == 'AREA'" class="errorTipText">{{ errorTipText }}</div>
      </section>
      <section v-for="(item, index) in customUserInfo" :key="index" class="c-flex-row c-aligni-center c-fs28 c-pv30 c-bd-b1-f6 c-p">
        <div v-if="item.require" class="c-fs32 c-fc-xmlred c-pa c-p-l0 c-p-t36">*</div>
        <input v-model="item.content" :placeholder="'请输入' + item.title" @focus="handerUserInfoFocus(index)" class="c-pl20 c-fs26 c-lh36 c-bd0 c-bg-transparent c-w0 c-flex-grow1" />
        <div v-if="errorTipName == `userInfo${index}`" class="errorTipText">{{ errorTipText }}</div>
      </section>
    </article>

    <footer class="c-ph90 c-pv30">
      <div v-if="showNextStep" @click="tapNext" class="c-bg-07C160 c-hh68 c-fc-white c-fs28 c-br6 c-flex-row c-flex-center">下一步</div>
      <div v-else @click="tapBind" class="c-bg-07C160 c-hh68 c-fc-white c-fs28 c-br6 c-flex-row c-flex-center">允许</div>
    </footer>
  </cj-popup>
</template>

<script>
import { mapState } from 'vuex';
import { utilJs, wxUtilJs } from '@/utils/common.js';
import { loadBMap } from '@/utils/loadBMap.js';
import { XAddress } from 'ckjrweb-mp-ui/src/components/index';

export default {
  components: {
    XAddress
  },

  props: {
    //是否不允许关闭弹窗不绑定手机号 大部分场景支持关闭，只有注册绑定或者平移登录场景不支持关闭
    notAllowClose: {
      type: Boolean,
      default: false
    },
    // 是否要走账号平移流程
    isRetrieve: {
      type: Boolean,
      default: false
    },
    //区域代理类型
    locateType: {
      type: Number,
      default: 1
    }
  },
  computed: {
    ...mapState({
      appConfig: state => state.oem_store.appConfig,
      showBindPhoneModal: state => state.oem_store.showBindPhoneModal
    }),
    showMobile() {
      return this.quickMobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    isNeedFillArea() {
      // 是否需要必填用户地区（旧版和新版区域代理都需要）,
      return this.locateType == 1 || this.locateType == 2;
    },
    showNextStep() {
      //开启自定义信息填写 || 需要填写用户地区
      return (this.customUserInfo.length || this.isNeedFillArea) && this.curStep == 1;
    }
  },
  watch: {
    showBindPhoneModal: {
      handler(val) {
        this.showBind = val;
        if (val) {
          this.init();
        }
      },
      immediate: true
    }
  },

  data() {
    return {
      showBind: true,
      isInit: 0,
      curStep: 1,
      isApp: false,
      isCheckAgreement: true,
      protocolInfo: null,
      quickMobile: '', // 快速绑定手机号
      codeImgInfo: {}, //手动绑定手机号的图形验证码
      mobile: '',
      imgCode: '',
      code: '',
      codeText: '获取验证码',
      customUserInfo: [], //更多填写信息内容
      isOpenGetLocation: true,
      showAddress: false,
      addrValue: [],
      addressData: [],
      errorTipName: '',
      errorTipText: ''
    };
  },
  created() {
    this._isLoading = false;
    this._validCodeTimeCon = null;
    this._companyId = utilJs.getCompanyIdByHerf();
    this.isOpenGetLocation = utilJs.isWeiXin();
    this.isInit = 0;
  },

  methods: {
    init() {
      this.isFillUserInfo = localStorage.getItem('isFillUserInfo') || 0;
      const customUserInfo = (localStorage.getItem('customUserInfo') && JSON.parse(localStorage.getItem('customUserInfo'))) || [];
      this.customUserInfo = this.isFillUserInfo == 1 && customUserInfo.length ? customUserInfo : [];
      this.enableAreaAgent = localStorage.getItem('enableAreaAgent') || 0;
      this.enableXhAreaAgent = localStorage.getItem('enableXhAreaAgent') || 0;
      this.enableWriteAddress = localStorage.getItem('enableWriteAddress') || 0;
      this._companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
      this.isApp = utilJs.isAndroidApp() || utilJs.isIOSAppALL();
      this.curStep = 1;
      this._userCount = 1;
      this._userList = [];
      this._countNum = 60;

      //只初始化一次，防止多次请求
      if (this.isInit == 1) {
        return;
      }
      utilJs.postMethod(`${global.apiurl}platform/getMobileByUnionId`, {}, res => {
        this.isInit = 1;
        this.showBind = true;
        this.quickMobile = res.mobile || '';
        this.mobile = this.quickMobile;
        this.code = res.code || '';
        //无法快速绑定手机号的时候，才需要获取图形验证码
        if (!this.quickMobile) {
          this.initOtherMobile();
        }
      });
    },
    /**
     * 根据手机号查找当前手机号的用户数量，用户判断是否需要合并账号
     */
    getUserCountByMobile() {
      //平移商家不走账号合并？
      if (this.isRetrieve) {
        return Promise.resolve();
      }
      return new Promise(resolve => {
        utilJs.getMethod(`${global.apiurl}common/getCustomerUserInfo?companyId=${this._companyId}&mobile=${this.mobile}`, res => {
          const userList = [...res.currentUserInfo, ...res.userInfo];
          this._userList = this.removeSomeId(userList);
          this._userCount = this._userList.length;
          resolve();
        });
      });
    },
    removeSomeId(arr) {
      // 去重
      if (!arr || !arr.length) {
        return [];
      }
      let map = new Map();
      for (let item of arr) {
        if (!map.has(item.userId)) {
          map.set(item.userId, item);
        }
      }
      return [...map.values()];
    },
    //关闭弹窗，清空定时器
    handerChose() {
      clearInterval(this._validCodeTimeCon);
      this._validCodeTimeCon = null;
      this.$store.commit("updateShowBindPhoneModal", {
        showBindPhoneModal: false
      });
    },
    //点击下一步
    async tapNext() {
      const errorTip = this.submitCheck();
      if (errorTip) {
        this.$showCjToast(errorTip);
        return;
      }
      await this.checkMobileCode();
      this.curStep = 2;
    },
    checkMobileCode() {
      const data = {
        mobile: this.mobile,
        code: this.code
      }
      return new Promise((resolve) => {
        utilJs.postMethod(`${global.apiurl}members/verifyMobile`, data, () => {
          resolve();
        });
      })
    },
    async tapBind() {
      const errorTip = this.submitCheck();
      if (errorTip) {
        this.$showCjToast(errorTip);
        return;
      }
      //平移用户绑定手机号
      if (this.isRetrieve) {
        this.bindRetrieveAccount();
        return;
      }
      await this.getUserCountByMobile();
      const bindData = {
        mobile: this.mobile,
        code: this.code,
        customUserInfo: this.isFillUserInfo == 1 ? this.customUserInfo : null
      };
      if (this.isNeedFillArea) {
        // 必填用户所在地
        const provinceId = this.addrValue[0];
        const cityId = this.addrValue[1];
        const areaId = this.addrValue[2];
        const address = { provinceId, cityId, areaId };
        bindData.address = address;
      }
      //多账号的话走合并流程
      if (this._userCount > 1) {
        this.goMergeUser(bindData);
        return;
      }
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;

      utilJs.postMethod(
        `${global.apiurl}members/bindMobile`,
        bindData,
        res => {
          localStorage.setItem('uMobile', this.mobile);
          this.bindGetIntegration();
          this._isLoading = false;
          this.$showCjToast({
            text: '绑定成功',
            type: 'success'
          });
          this.$emit('finishBindMobile');
          //绑定成功，关闭弹窗
          this.$store.commit('updateShowBindPhoneModal', {
            showBindPhoneModal: false
          });
          //图文课程绑定手机号成功
          this.$store.commit('updateHasModalBindPhone', {
            hasModalBindPhone: true
          });
        },
        () => {
          this._isLoading = false;
        }
      );
    },
    goMergeUser(bindData) {
      //合并账号前先校验下手机号验证码
      let data = {
        mobile: this.mobile,
        verifyCode: this.code,
        fromApp: this.fromChannel == 14 ? 'dy' : 'qt',
        companyId: this._companyId
      };
      utilJs.postMethod(global.apiurl + 'accountConnect/checkSendCode', data, () => {
        //打开合并账号弹窗
        this.$store.commit('updateBindData', bindData);
        this.$store.commit('updateUserInfoList', this._userList);
        this.$store.commit('updateShowMergeUserModal', true);
      });
    },

    submitCheck() {
      //校验第一步的手机号和验证码
      if (!this.quickMobile && !this.mobile) {
        return '手机号不能为空';
      }
      if (!this.quickMobile && !this.imgCode) {
        return '图片验证码不能为空';
      }
      if (!this.quickMobile && !this.code) {
        return '验证码不能为空';
      }
      if (!this.quickMobile && !this.isCheckAgreement) {
        return '请先同意相关协议';
      }
      //只有一步，则结束校验
      if (this.curStep == 1) {
        return '';
      }
      //如果有第二步this.curStep == 2，校验第二步的自定义信息和地址
      //校验区域地址,如果区域地址为空，则提示
      if (this.isNeedFillArea && !this.addrValue.length) {
        this.errorTipName = 'AREA';
        this.errorTipText = '请选择地址';
        return this.errorTipText;
      }
      //校验自定义信息
      for (let i = 0; i < this.customUserInfo.length; i++) {
        const item = this.customUserInfo[i];
        if (!item.content && item.require) {
          this.errorTipName = `userInfo${i}`;
          this.errorTipText = '未填写';
          return this.errorTipText;
        }
        if (item.content.length > 20) {
          this.errorTipName = `userInfo${i}`;
          this.errorTipText = `不能超过20个字符`;
          return this.errorTipText;
        }
      }
      return '';
    },
    handerHideAddress() {
      if (this.addrValue.length && this.errorTipName == 'AREA') {
        this.errorTipName = '';
        this.errorTipText = '';
      }
    },
    handerUserInfoFocus(index) {
      if (this.errorTipName == `userInfo${index}`) {
        this.errorTipName = '';
        this.errorTipText = '';
      }
    },
    //平移平台找回账号绑定手机号
    bindRetrieveAccount() {
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;
      const data = {
        mobile: this.mobile,
        imgCode: this.imgCode,
        code: this.code,
        isCheckAgreement: this.isCheckAgreement,
        customUserInfo: this.customUserInfo,
        area: this.addrValue.length ? this.addrValue[0] : '',
        areaDetail: this.addrValue.length ? this.addrValue[1] : '',
        areaDetail2: this.addrValue.length ? this.addrValue[2] : ''
      };
      utilJs.postMethod(
        `${global.apiurl}members/newBindMobile`,
        data,
        res => {
          this._isLoading = false;
          localStorage.setItem('uMobile', this.mobile);
          this.bindGetIntegration();
          if (res.account) {
            // 显示合并账号弹窗
            this.$store.commit('updateUserAccountList', res.account);
            this.$store.commit('updateBindVerificationCode', this.code);
            this.$store.commit('updateShowMergeUserModal', true);
            return;
          }
          this.$showCjToast({
            text: '绑定成功',
            type: 'success'
          });
          this.$store.commit('updateShowBindPhoneModal', {
            showBindPhoneModal: false
          });
        },
        failRes => {
          this._isLoading = false;
        }
      );
    },
    //绑定手机领取积分
    bindGetIntegration() {
      if (this._companyAuth && this._companyAuth.enableBindPhonePoint != 1) {
        return;
      }
      //积分来源 1. 分享视频，2：观看视频，3：分享音频，4：观看音频，14：分享文章 51：分享知识套餐 52：分享专刊 53：分享直播 54：观看直播 55：绑定手机
      let data = {
        cId: -1,
        extId: -1,
        pointFrom: 55,
        duration: -1
      };
      utilJs.postMethod(`${global.apiurl}common/getPoints`, data);
    },
    //其他手机号输入流程***START***
    initOtherMobile() {
      this.mobile = '';
      this.code = '';
      this.tapGetImgCode();
      if (this.isApp) {
        this.getAppProtocols();
      } else {
        this.getProtocol();
      }
      this.getAreaListForAgent();
    },
    tapGetImgCode() {
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;
      utilJs.getMethod(
        `${global.apiurl}common/captcha`,
        res => {
          this.codeImgInfo = res;
          this._isLoading = false;
        },
        failRes => {
          this._isLoading = false;
        }
      );
    },
    tapUseOtherMobile() {
      this.quickMobile = '';
      this.initOtherMobile();
    },
    tapGetVcode() {
      if (!this.mobile) {
        this.$showCjToast('手机号不能为空');
        return;
      }
      if (!this.imgCode) {
        this.$showCjToast('图片验证码不能为空');
        return;
      }
      if (this._isLoading) {
        return;
      }
      if (this._countNum != 60) {
        return;
      }
      clearInterval(this._validCodeTimeCon);
      this._countNum = 60;
      this._isLoading = true;
      this.codeText = '获取验证码';
      utilJs.postMethod(
        global.apiurl + 'members/sendCode',
        {
          mobile: this.mobile,
          isBindMobile: !this.isRetrieve,
          captcha: this.imgCode,
          captchaKey: this.codeImgInfo.key
        },
        res => {
          this._isLoading = false;
          if (res.errMsg) {
            this.$showCjToast({
              text: res.errMsg,
              type: 'warn'
            });
            return;
          }
          this.startCountDown();
        },
        () => {
          this._isLoading = false;
        }
      );
    },
    startCountDown() {
      clearInterval(this._validCodeTimeCon);
      this._countNum = 60;
      this._validCodeTimeCon = setInterval(() => {
        this.codeText = `${this._countNum}s后获取`;
        this._countNum--;
        if (this._countNum <= 0) {
          clearInterval(this._validCodeTimeCon);
          this._countNum = 60;
          this.codeText = '获取验证码';
        }
      }, 1000);
    },
    //其他手机号输入流程***END***
    //用户协议相关***START***
    getAppProtocols() {
      utilJs.getMethod(`${global.apiurl}app/getAppUseAndPrivacyProtocols`, res => {
        this.isCheckAgreement = false;
        this.protocolInfo = res || null;
      });
    },
    getProtocol() {
      utilJs.getMethod(`${global.apiurl}protocols/getProtocolByProdType?prodType=-2`, res => {
        this.protocolInfo = res.protocol && res.protocol.length > 0 ? res.protocol : null;
        this.isCheckAgreement = res.relatesType == 1 ? true : false;
      });
    },
    tapToAppProtocol(url) {
      if (!url) return;
      window.location.href = url;
    },
    tapProtocol(item) {
      this.$routerGo(this, 'push', { path: `/homePage/agent/protocolInfo`, query: { protocolId: item.protocolId } });
    },
    tapChangeAgreement() {
      this.isCheckAgreement = !this.isCheckAgreement;
    },
    //用户协议相关***END***
    //定位地址选择相关***START***
    getAreaListForAgent() {
      if (!this.isNeedFillArea) {
        return;
      }
      utilJs.getMethod(`${global.apiurl}common/getAreaListForAgent`, res => {
        this.addressData = res.data;
        // this.getInfo();
      });
    },
    //获取个人所在地
    getInfo() {
      utilJs.getMethod(global.apiurl + 'members', res => {
        if (res.provinceId && res.cityId && res.areaId) {
          this.addrValue = [`${res.provinceId}`, `${res.cityId}`, `${res.areaId}`];
        }
        console.log('---this.addressData--', this.addressData);
        console.log('---this.addrValue--', this.addrValue);
      });
    },
    tapGetLocation() {
      wxUtilJs
        .getLocation()
        .then(res => {
          return this.getBdAddress(res.longitude, res.latitude);
        })
        .catch(() => {
          this.isOpenGetLocation = false;
          this.$showCjToast('自动定位失败，请手动选择地址');
        });
    },
    getBdAddress(longitude, latitude) {
      /* eslint-disable */
      let that = this;
      this.$loading.hide();
      this.$loading.show({
        text: '定位中'
      });
      loadBMap().then(BMap => {
        let point = new BMap.Point(longitude, latitude);
        let gc = new BMap.Geocoder();
        gc.getLocation(point, function(rs) {
          that.$loading.hide();
          const addComp = rs.addressComponents;
          // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
          that.getAddressId(addComp);
        });
      });
    },
    getAddressId(addComp) {
      let provinceId = '';
      let cityIds = [];
      let cityId = '';
      let areaIds = [];
      let areaId = '';
      this.addressData &&
        this.addressData.forEach(item => {
          item.name = ['北京', '天津', '上海', '重庆'].includes(item.name) ? item.name + '市' : item.name;
          if (item.name == addComp.province && item.level == 1) {
            provinceId = item.value;
          }
          if (item.name == addComp.city && item.level == 2) {
            // 防止市名重复
            cityIds.push(item);
          }
          if (item.name == addComp.district && item.level == 3) {
            // 防止区名重复
            areaIds.push(item);
          }
        });
      cityId = this.getAddId(cityIds, provinceId);
      areaId = this.getAddId(areaIds, cityId);
      // 如果定位获取到的数据不完整，就需要手动使用地址选择权
      if (!provinceId || !cityId || !areaId) {
        this.addrValue = [];
        this.isOpenGetLocation = false;
        this.$showCjToast('自动定位失败，请手动选择地址');
        return;
      }
      this.addrValue = [`${provinceId}`, `${cityId}`, `${areaId}`];
    },
    getAddId(list, id) {
      if (list && list.length == 1) {
        return list[0].value;
      }
      const info = list.find(i => i.parent == id);
      const currentId = (info && info.value) || '';
      return currentId;
    },
    getAddressName() {
      let provinceStr = '';
      let cityStr = '';
      let areaStr = '';
      if (!this.addressData) {
        return '';
      }
      console.log('this.addrValue', this.addrValue);
      this.addressData.forEach(item => {
        if (item.value == this.addrValue[0]) {
          provinceStr = item.name;
        }
        if (item.value == this.addrValue[1]) {
          cityStr = item.name;
        }
        if (item.value == this.addrValue[2]) {
          areaStr = item.name;
        }
      });
      return provinceStr + ' ' + cityStr + ' ' + areaStr;
    },
    handerShowAddress() {}
    //定位地址选择相关***END***
  }
};
</script>

<style scoped>
.errorTipText {
  position: absolute;
  bottom: 0;
  font-weight: 400;
  font-size: 0.45rem;
  color: #ff300c;
  left: 0.5rem;
  width: 100%;
  border-bottom: 1px solid;
}
</style>
